//
//  LCYDownloadManager.m
//  EPA
//
//  Created by lanou3g on 16/4/27.
//  Copyright © 2016年 liu. All rights reserved.
//

#import "LCYDownloadManager.h"

@interface DownloadManagerTask : NSObject
@property (nonatomic,strong) LCYRadioDetailModel *model;
@property (nonatomic,strong) MusicDownloadTask *downloadTask;
@end
@implementation DownloadManagerTask

- (NSString *)description {
    return self.model.title;
}

@end




@implementation LCYDownloadManager

+ (instancetype)shareDownload {
    static LCYDownloadManager *manager = nil;
    @synchronized(self) {
        if (!manager) {
            manager = [[LCYDownloadManager alloc]init];
            manager.downloadArray = [NSMutableArray array];
        }
    }
    return manager;
}

/// 添加下载任务
- (void)addDownloadTask:(LCYRadioDetailModel *)model Progress:(ProgressBlock)proBlock Complate:(ComplateBlock)comBlock {
    BOOL isContain = NO;
    for (DownloadManagerTask *task in self.downloadArray) {
        if ([task.model.title isEqualToString:model.title]) {
            isContain = YES;
            return;
        }
    }
    
    // 包括就不下载
    if (isContain) {
        return;
    }
    // 下载
    MusicDownloadTask *musicTask = [[MusicDownloadTask alloc]init];
    [musicTask downloadUrl:[NSURL URLWithString:model.musicUrl] progresBlock:proBlock complate:comBlock];
    
    /// 添加到数组中
    DownloadManagerTask *downloadTask = [[DownloadManagerTask alloc]init];
    downloadTask.model = model;
    downloadTask.downloadTask = musicTask;
    [self.downloadArray addObject:downloadTask];
    
}


/// 当前下载任务个数
- (NSInteger)count {
    return self.downloadArray.count;
}
/// 取cell的标题
- (NSString *)getTitleWithIndex:(NSInteger)index {
    DownloadManagerTask *task = self.downloadArray[index];
    return task.model.title;
}
/// 设置block
- (void)setProgressBlock:(ProgressBlock)proBlock ComplateBlock:(ComplateBlock)comBlock Index:(NSInteger)index {
    DownloadManagerTask *task = self.downloadArray[index];
    [task.downloadTask setProgressBlock:proBlock];
    [task.downloadTask setComplateBlock:^(NSString *path) {
        [self.downloadArray removeObjectAtIndex:index];
        /// 发送通知
        [[NSNotificationCenter defaultCenter]postNotificationName:@"downloadReloadData" object:nil];
    }];
    
}




@end
